const { getDb } = require('../database');

/**
 * 扫描并处理到期的定时发布：
 * - 条件：publish_news.pub_state = 0 且 wait_pub_time <= 当前时间
 * - 操作：设置 publish_time = 当前时间、pub_state = 1；同步 news.pub_time、news.is_published = 1
 */
async function processDuePublishes() {
  const db = await getDb();
  // 查找到期的定时发布
  const dueRows = await db.all(
    "SELECT id, news_id FROM publish_news WHERE pub_state = 0 AND wait_pub_time IS NOT NULL AND datetime(wait_pub_time) <= datetime('now')"
  );
  if (!dueRows || dueRows.length === 0) return;

  await db.run('BEGIN TRANSACTION');
  try {
    for (const row of dueRows) {
      const publishId = row.id;
      const newsId = row.news_id;
      // 更新发布记录为已发布
      await db.run(
        "UPDATE publish_news SET publish_time = datetime('now'), pub_state = 1 WHERE id = ?",
        [publishId]
      );
      // 同步 news 表的发布时间与发布状态
      await db.run(
        "UPDATE news SET pub_time = datetime('now'), is_published = 1 WHERE id = ?",
        [newsId]
      );
    }
    await db.run('COMMIT TRANSACTION');
  } catch (err) {
    await db.run('ROLLBACK TRANSACTION');
    throw err;
  }
}

/**
 * 启动定时处理器：每分钟检查一次到期的发布记录。
 */
function schedulePublishProcessor() {
  console.log('[publish-scheduler] 已启用：每分钟检查到期的定时发布');
  // 服务器启动后先执行一次
  processDuePublishes().catch((e) => console.error('[publish-scheduler] 首次执行异常:', e.message));
  // 每分钟执行一次
  const MINUTE_MS = 60 * 1000;
  setInterval(() => {
    processDuePublishes().catch((e) => console.error('[publish-scheduler] 执行异常:', e.message));
  }, MINUTE_MS);
}

module.exports = {
  schedulePublishProcessor,
};